<template>
  <div class="app-container machineContainer">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <!-- <el-form-item class="pull-right">
                    <span>机台总数 {{machine_num}} 台</span>
        </el-form-item>-->
        <el-form-item>
          <el-select
            filterable
            placeholder="选择门店"
            v-model="formInline.store_id"
            @change="storeChangeF"
            style="width:300px"
          >
            <el-option
              v-for="item in store_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-select filterable placeholder="选择区域" v-model="formInline.area_id" style="width:100px">
            <el-option v-for="item in area_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select filterable placeholder="选择类型" v-model="type_id" style="width:100px">
            <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.machine_id"
            placeholder="请输入机台ID"
            @keyup.enter.native="searchClick"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <transition name="fade" mode="out-in" :key="formInline.type_id">
        <el-table
          highlight-current-row
          :data="list"
          v-loading.body="listLoading"
          border
          size="small"
        >
          <el-table-column align="center" label="序号" width="50">
            <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
          </el-table-column>
          <el-table-column align="center" label="门店" prop="name"></el-table-column>
          <el-table-column align="center" label="区域" prop="area_name" width="150"></el-table-column>
          <el-table-column align="center" label="机台ID" prop="id" width="150"></el-table-column>
          <el-table-column align="center" label="机台编号" prop="no" width="150"></el-table-column>
          <el-table-column align="center" label="机台类型" prop="type_name"></el-table-column>
          <el-table-column v-if="formInline.type_id==3" align="center" label="业务类型" prop="sub_name"></el-table-column>
          <!-- 列表的操作按钮 -->
          <el-table-column align="center" label="操作" width="240">
            <template slot-scope="scope">
              <el-button
                v-show="formInline.type_id!=3 && formInline.type_id!=4"
                @click="seeEditClick(scope.row)"
                type="primary"
                icon="el-icon-info"
                size="mini"
              ></el-button>
              <el-button
                @click="addEditClick(scope.row)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
              ></el-button>
              <el-button
                @click="delClick(scope.row,scope.$index)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
              <el-button
                v-show="formInline.type_id==3"
                type="primary"
                plain
                size="mini"
                @click="setClick(scope.row)"
              >配置套餐</el-button>
            </template>
          </el-table-column>
        </el-table>
      </transition>

      <!-- 弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        title="机台详细信息"
        :visible.sync="infoDialog"
        width="400px"
      >
        <div style="font-size:16px;text-align:center">机台当前币数：{{currentCoins}}</div>
      </el-dialog>
      <!-- 配置套餐弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        title="配置套餐"
        :visible.sync="mealDialog"
        width="800px"
        class="dialog_table_small"
      >
        <div class="title">已选套餐</div>
        <div class="check_meal">
          <div class="check_meal_list">
            <div
              class="check_meal_item"
              :class="{old:p.isOld==1,past:p.overdue==1}"
              v-for="(p,i) of package_list"
              :key="p.package_id"
            >
              <span>{{p.package_name}}</span>
              <span class="el-icon-close" @click="delCheck(i)"></span>
              <img v-if="p.overdue==1" src="../../assets/images/past.png" />
            </div>
          </div>
        </div>
        <div style="display:flex;justify-content:space-between;margin-bottom:10px">
          <div>
            <el-autocomplete
              size="small"
              v-model="searchValue"
              style="width:200px;margin-top:10px;"
              :fetch-suggestions="querySearch"
              placeholder="请输入要搜索的内容"
              :trigger-on-focus="false"
              valueKey="name"
            ></el-autocomplete>
            <div class="el-button--small el-button el-button--primary" @click="mealSearchClick">
              <span style="font-size:14px">搜 索</span>
            </div>
          </div>
          <!-- <span style="color:#f00;margin-top:20px">注：一种业务类型最多配置9个套餐</span> -->
        </div>
        <el-table
          highlight-current-row
          max-height="400px"
          :data="mealList"
          v-loading.body="listLoading"
          border
          size="small"
        >
          <el-table-column align="center" label="序号" width="50">
            <template slot-scope="scope">
              <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="套餐名称" prop="name"></el-table-column>
          <el-table-column align="center" label="充值金额" prop="money"></el-table-column>
          <el-table-column align="center" label="获得币/星/次数" prop="get_values" width="100"></el-table-column>
          <el-table-column align="center" label="获得积分" prop="scores"></el-table-column>
          <!-- <el-table-column align="center" label='赠送' prop="give_values"></el-table-column> -->
          <el-table-column align="center" label="优先级" prop="sort"></el-table-column>
          <el-table-column align="center" label="角标" prop="recommend"></el-table-column>
          <el-table-column align="center" :render-header="renderHeader" width="70">
            <template slot-scope="scope">
              <el-checkbox
                v-model="scope.row.isCheck"
                @change="changeCheck(scope.row)"
                true-label="1"
                false-label="0"
                :disabled="allCheck==1&&scope.row.isCheck==0"
              ></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
        <div style="padding: 20px 0">
          <div class="pull-right">
            <el-button type="primary" size="small" @click="saveMealClick">保存</el-button>
          </div>
        </div>
      </el-dialog>
      <!-- 弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        :title="addTitle"
        :visible.sync="addDialog"
        width="600px"
        @close="callOf('saveForm')"
      >
        <el-form
          :model="saveForm"
          :inline="true"
          ref="saveForm"
          :rules="rules"
          style="width:760px;margin-bottom:20px;"
        >
          <el-form-item label="所属门店" prop="store_id">
            <el-select
              style="width: 255px"
              size="mini"
              @change="addStoreChangeF"
              v-model="saveForm.store_id"
              filterable
              :disabled="isAmend"
            >
              <el-option
                v-for="item in add_store_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属区域" prop="area_id">
            <el-select
              style="width: 115px"
              size="mini"
              v-model="saveForm.area_id"
              filterable
              :disabled="isAmend"
            >
              <el-option
                v-for="item in add_area_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="机台类型" prop="type_id">
            <el-select
              style="width: 255px"
              size="mini"
              v-model="saveForm.type_id"
              filterable
              :disabled="isAmend"
            >
              <el-option
                v-for="item in type_list"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="机台编号" prop="no">
            <el-input size="mini" v-model="saveForm.no" placeholder="请输入机台编号" style="width: 115px"></el-input>
          </el-form-item>
          <el-form-item v-if="saveForm.type_id==3" label="业务类型" prop="sub_type_id" required>
            <el-select style="width: 255px" size="mini" v-model="saveForm.sub_type_id" filterable>
              <el-option
                v-for="item in sub_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <span
            v-show="isAmend&&saveForm.type_id==3"
            class="pull-left"
            style="font-size: 14px;color:#f00"
          >注：如果修改业务类型则该机台所有套餐将重新配置</span>
          <el-button type="primary" @click="saveClick('saveForm')">保存</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination
        class="pull-left"
        background
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="20"
        layout="prev, pager, next, jumper"
        :total="totalDataNumber"
      ></el-pagination>
      <div class="pull-right">
        <!-- <router-link :to="{name:'information/machineType'}">
                    <el-button type="primary" size="small">机台类型管理</el-button>
        </router-link>-->
        <el-button type="primary" size="small" @click="addEditClick()">新增机台</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getList,
  del,
  getStore,
  getArea,
  getInfo,
  save,
  getMeal,
  getCardMeal,
  saveCardMeal,
} from "@/api/information/deviceManage";
import { num1to255, nullOr1to255 } from "@/utils/validate";
export default {
  data() {
    const validateVal = (rule, value, callback) => {
      if (!num1to255(value)) {
        callback(new Error("请输入1-255数字"));
      } else {
        callback();
      }
    };
    return {
      default_no: "",
      store_list: [], //筛选
      area_list: [], //筛选
      type_list: [
        { id: 2, name: "存币机" },
        { id: 0, name: "提币机" },
        { id: 3, name: "发卡机" },
        { id: 4, name: "新发卡机" },
      ],
      sub_list: [
        { id: "0", name: "会员卡业务" },
        { id: "1", name: "次卡业务" },
        { id: "2", name: "星星卡业务" },
      ],
      add_store_list: [],
      add_area_list: [],
      package_list: [],
      old_package_list: [],
      mealList: [],
      allMealList: [],
      multipleSelection: [],
      list: null,
      listLoading: false,
      infoDialog: false,
      addDialog: false,
      mealDialog: false,
      isAmend: false,
      addTitle: "",
      searchValue: "",
      cardMachineId: "",
      allCheck: 0,
      currentPage: 1,
      currentCoins: 0,
      totalDataNumber: 0,
      type_id: 2,
      formInline: {
        store_id: "",
        area_id: "",
        type_id: 2,
        machine_id: "",
        page: 0,
      },
      saveForm: {
        id: "",
        store_id: "",
        area_id: "",
        type_id: 2,
        sub_type_id: 0,
        no: "",
      },
      rules: {
        store_id: [
          { required: true, message: "请选择门店", trigger: "change" },
        ],
        area_id: [{ required: true, message: "请选择区域", trigger: "change" }],
        type_id: [
          { required: true, message: "请选择机台类型", trigger: "change" },
        ],
        no: [{ required: true, message: "请输入机台编号", trigger: "blur" }],
      },
      //addEditDialog: false,
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.list) {
        vm.fetchData();
        //vm.getBrandList();
        vm.getStoreF(); //搜索条件的门店
        // vm.getTypeF();//搜索条件的类型
      }
    });
  },
  methods: {
    getStoreF() {
      getStore({ category_id: 411 }).then((response) => {
        this.store_list = response;
        // this.formInline.store_id = response[0].id;
        let data = response.filter(
          (res) => res.id == this.$store.getters.optionId
        );
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
        } else {
          if (this.store_list.length > 0) {
            this.formInline.store_id = this.store_list[0].id;
          }
        }
        this.storeChangeF();
      });
    },
    storeChangeF() {
      //console.log(i,area_id,store_id,9999)
      getArea({ sid: this.formInline.store_id }).then((response) => {
        response.unshift({ id: "", name: "全部区域" });
        this.area_list = response;
        this.formInline.area_id = response[0].id;
        if (this.list == null) {
          this.searchClick();
        }
      });
    },
    addStoreChangeF(id) {
      //console.log(i,area_id,store_id,9999)
      getArea({ sid: this.saveForm.store_id }).then((res) => {
        this.add_area_list = res;
        if (this.isAmend) {
          this.saveForm.area_id = id;
        } else {
          this.saveForm.area_id = res[0].id;
        }
      });
    },
    seeEditClick(row) {
      //console.log(row)
      this.currentCoins = 0;
      getInfo({ id: row.id, type_id: row.type_id }).then((res) => {
        //console.log(res)
        if (res.code == 1) {
          this.currentCoins = res.message.stock_val1;
        }
        this.infoDialog = true;
      });
    },
    //配置套餐弹窗
    setClick(row) {
      // console.log(row)
      this.package_list = [];
      this.allMealList = [];
      this.mealList = [];
      this.old_package_list = [];
      this.cardMachineId = "";
      this.searchValue = "";
      getMeal({ id: row.id }).then((res) => {
        // console.log(res)
        if (res.code == 1) {
          res.message.forEach((val) => {
            val.isOld = 1;
          });
          this.package_list = res.message;
          this.old_package_list = JSON.parse(JSON.stringify(res.message));
          this.cardMachineId = row.id;
          getCardMeal({
            type: row.sub_type_id,
            name: "",
            is_effective: "1",
            is_enable: "1",
          }).then((res) => {
            res.forEach((val) => {
              (val.recommend = val.show_recommend == 1 ? "店长推荐" : "无"),
                (val.isCheck = "0");
              val.money /= 100;
              this.package_list.forEach((item) => {
                // console.log(item)
                if (item.package_id == val.id) {
                  val.isCheck = "1";
                  return false;
                }
              });
            });
            this.allMealList = res;
            this.mealList = JSON.parse(JSON.stringify(res));
            this.mealDialog = true;
          });
        }
      });
    },
    //配置套餐弹窗表头
    renderHeader(h, { column }) {
      var self = this;
      return h("el-checkbox", {
        style: "font-size:12px;",
        props: { label: "全选", "true-label": 1, value: self.allCheck == 1 },
        on: {
          change: (column, $event) => {
            if (self.allCheck == 1) {
              self.allCheck = 0;
            } else {
              self.allCheck = 1;
            }
            self.changeAllCheck();
          },
        },
      });
    },
    delCheck(i) {
      let delMeal = this.package_list.splice(i, 1);
      this.mealList.forEach((val) => {
        if (val.id == delMeal[0].package_id) {
          val.isCheck = "0";
          return false;
        }
      });
    },
    changeCheck(row) {
      if (row.isCheck == 1) {
        let old = this.old_package_list.filter(
          (item) => item.package_id == row.id
        );
        if (old.length) {
          this.package_list.push({
            package_id: row.id,
            package_name: row.name,
            isOld: 1,
          });
        } else {
          this.package_list.push({
            package_id: row.id,
            package_name: row.name,
            isOld: 0,
          });
        }
      } else {
        this.package_list.forEach((val, i) => {
          if (val.package_id == row.id) {
            this.package_list.splice(i, 1);
            return false;
          }
        });
      }
    },
    //配置套餐全选
    changeAllCheck() {
      if (this.allCheck) {
        let num = 50 - this.package_list.length;
        this.mealList.forEach((val) => {
          if (num <= 0) {
            return false;
          }
          if (val.isCheck == 0) {
            val.isCheck = "1";
            let old = this.old_package_list.filter(
              (item) => item.package_id == val.id
            );
            if (old.length) {
              this.package_list.push({
                package_id: val.id,
                package_name: val.name,
                isOld: 1,
              });
            } else {
              this.package_list.push({
                package_id: val.id,
                package_name: val.name,
                isOld: 0,
              });
            }
            // this.package_list.push({package_id:val.id,package_name:val.name})
            num--;
          }
        });
        // console.log(this.mealList)
      } else {
        this.mealList.forEach((val) => {
          val.isCheck = 0;
          this.package_list.forEach((item, i) => {
            if (item.package_id == val.id) {
              this.package_list.splice(i, 1);
            }
          });
        });
      }
    },
    //配置套餐搜索
    querySearch(queryString, cb) {
      var allMealList = this.allMealList;
      var results = queryString
        ? allMealList.filter(this.createFilter(queryString))
        : allMealList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.name.indexOf(queryString) >= 0;
      };
    },
    mealSearchClick() {
      this.mealList = [];
      if (this.searchValue == "") {
        this.mealList = this.allMealList;
        return;
      }
      let list = this.allMealList.filter(
        (item) => item.name.indexOf(this.searchValue) >= 0
      );
      list.forEach((val) => {
        val.isCheck = "0";
        this.package_list.forEach((item) => {
          if (item.package_id == val.id) {
            val.isCheck = "1";
            return false;
          }
        });
      });
      this.mealList = list;
    },
    //配置套餐保存
    saveMealClick() {
      let package_list = [];
      this.package_list.forEach((val) => {
        package_list.push(val.package_id);
      });
      saveCardMeal({ id: this.cardMachineId, package_list }).then((res) => {
        this.$message({ type: "success", message: res.message });
        if (res.code == 1) {
          this.mealDialog = false;
        }
      });
    },
    // 编辑和新增弹窗
    addEditClick(row) {
      // this.editIndex = id ? index : '';
      this.addTitle = row ? "修改机台" : "新增机台";
      this.isAmend = row ? true : false;
      this.saveForm.type_id = row ? row.type_id / 1 : this.formInline.type_id;
      this.saveForm.no = row ? row.no : "";
      this.saveForm.id = row ? row.id : "";
      this.saveForm.sub_type_id = row ? row.sub_type_id : "0";
      let area_id = row ? row.area_id : "";
      getStore({ category_id: 411 }).then((res) => {
        if (res[0].name === "全门店") res.splice(0, 1);
        this.add_store_list = res;
        //console.log(res,this.add_store_list)
        this.saveForm.store_id = row
          ? row.store_id
          : this.formInline.store_id
          ? this.formInline.store_id
          : res[0].id;
        this.addStoreChangeF(area_id);
      });
      this.addDialog = true;
    },
    delClick(row, index) {
      if (row.type_id < 3) {
        getInfo({ id: row.id, type_id: row.type_id }).then((res) => {
          if (res.code == 1 && res.message.stock_val1 == 0) {
            this.$confirm("此操作删除, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              del({ id: row.id, type_id: row.type_id, is_del: 1 }).then(
                (response) => {
                  if (response.code == 1) {
                    this.list.splice(index, 1);
                    this.$message({
                      type: "success",
                      message: "删除成功!",
                    });
                  }
                }
              );
            });
          } else {
            this.$message.error("当前机台币数不为0，无法删除");
          }
        });
      } else {
        this.$confirm("此操作删除, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          del({ id: row.id, type_id: row.type_id, is_del: 1 }).then(
            (response) => {
              if (response.code == 1) {
                this.list.splice(index, 1);
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              }
            }
          );
        });
      }
    },
    // 提交
    saveClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          save(this.saveForm).then((response) => {
            //console.log(response)
            if (response.code == 1) {
              this.$refs["saveForm"].resetFields();
              this.$message({ type: "success", message: response.message });
              this.addDialog = false;
              this.fetchData();
            }
          });
        }
      });
    },
    // 搜索
    searchClick() {
      this.formInline.type_id = this.type_id;
      this.fetchData();
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getList(this.formInline)
        .then((res) => {
          // this.totalDataNumber = response.total * 1;
          // this.machine_num = response.total
          //console.log(res)
          if (res.code == 1) {
            this.totalDataNumber = res.message.page_toal / 1;
            res.message.data.forEach((val) => {
              val.type_name =
                val.type_id == 2
                  ? "存币机"
                  : val.type_id == 0
                  ? "提币机"
                  : val.type_id == 3
                  ?"发卡机":"新发卡机"
              val.sub_name =
                val.sub_type_id && val.sub_type_id == 0
                  ? "会员卡"
                  : val.sub_type_id == 1
                  ? "次卡"
                  : "星星卡";
            });
            this.list = res.message.data;
          }
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    // 分页
    handleCurrentChange(val) {
      this.listLoading = true;
      this.formInline.page = val - 1;
      getList(this.formInline).then((res) => {
        if (res.code == 1) {
          this.totalDataNumber = res.message.page_toal / 1;
          res.message.data.forEach((val) => {
            val.type_name =
              val.type_id == 2
                ? "存币机"
                : val.type_id == 0
                ? "提币机"
                : "发卡机";
            val.sub_name =
              val.sub_type_id && val.sub_type_id == 0
                ? "会员卡"
                : val.sub_type_id == 1
                ? "次卡"
                : "星星卡";
          });
          this.list = res.message.data;
        }
        this.listLoading = false;
      });
    },
    // 表单认证
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //关闭弹框重置
    callOf(formName) {
      //this.addEditDialog = false;
      this.saveForm.id = "";
      this.saveForm.store_id = "";
      this.saveForm.area_id = "";
      this.saveForm.type_id = "";
      this.saveForm.sub_type_id = 0;
      this.saveForm.no = "";
      this.$refs[formName].resetFields();
    },
  },
  computed: {
    isAllCheck: function () {
      // return  this.package_list.length>=9?1:0
      let num = 0;
      this.mealList.forEach((val) => {
        if (val.isCheck == 1) {
          num++;
        }
      });
      if (
        num >= 50 ||
        (this.mealList.length != 0 && num == this.mealList.length) ||
        this.package_list.length >= 50
      ) {
        return 1;
      } else {
        return 0;
      }
    },
  },
  watch: {
    isAllCheck(val) {
      this.allCheck = val;
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scope>
div.check_meal {
  border: 1px solid #ccc;
  padding: 10px 10px 0;
  height: 96px;
  overflow: auto;
  div.check_meal_list {
    display: flex;
    flex-wrap: wrap;
    div.check_meal_item {
      font-size: 12px;
      border: 1px solid #409eff;
      color: #409eff;
      border-radius: 5px;
      padding: 3px 5px;
      margin: 0 10px 10px 0;
      position: relative;
      .el-icon-close {
        font-size: 14px;
        margin-left: 5px;
        padding: 2px;
        cursor: pointer;
        &:hover {
          background-color: #409eff;
          color: #fff;
          border-radius: 50%;
        }
      }
      img {
        position: absolute;
        top: -1px;
        left: -2px;
        height: 26px;
      }
    }
    div.check_meal_item.old {
      color: #fff;
      background: #409eff;
      .el-icon-close {
        &:hover {
          background-color: #fff;
          color: #409eff;
        }
      }
    }
    div.check_meal_item.past {
      padding-left: 25px;
      border-color: #b3b3b3;
      background: #dbdbdb;
      color: #a2a2a2;
      .el-icon-close {
        &:hover {
          background-color: #bbb;
          color: #777;
        }
      }
    }
  }
}
</style>